package xxx;

import java.io.*;
import java.net.Socket;

public class ServerThread extends Thread{
    private Socket socket;
    public ServerThread(Socket socket){
        this.socket=socket;
    }
    @Override
    public void run() {
        try {
            InputStream is = socket.getInputStream();
            DataInputStream dis = new DataInputStream(is);
            while (true){
                try {
                    String message = dis.readUTF();
                    forwardAll(message);
                } catch (Exception e) {
                    System.out.println("有人下线了!~");
                    communicationServer.online.remove(socket);
                    dis.close();
                    socket.close();
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void forwardAll(String message) throws Exception {
        for (Socket onlinesocket : communicationServer.online) {
                    OutputStream os = onlinesocket.getOutputStream();
                    DataOutputStream dos = new DataOutputStream(os);
                dos.writeUTF(message);
                dos.flush();

        }
    }
}
